package com.lagou.filter;

import com.lagou.client.UserFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

/**
 * 令牌过滤器
 * @author xh
 * @date 2021/2/2 12:24
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();
        //调用邮件微服务前进行过滤
        if(uri.contains("/api/email")) {
            //获得Token
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> tokenList = cookies.get("token");
            String msg = "";
            if(tokenList != null && tokenList.size() > 0) {
                HttpCookie httpCookie = tokenList.get(0);
                String token = httpCookie.getValue();
                //调用用户微服务Token验证接口进行Token验证
                String email = userFeignClient.info(token);
                if(StringUtils.isEmpty(email)) {
                    //设置响应内容
                    msg = "token is invalid";
                    //设置响应状态码
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.writeWith(Mono.just(response.bufferFactory().wrap(msg.getBytes())));
                }
            } else {
                //设置响应内容
                msg = "token is without";
                //设置响应状态码
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.writeWith(Mono.just(response.bufferFactory().wrap(msg.getBytes())));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
